<template>
	<div id="add-edit-model">
		<el-dialog :title="titleCon" v-model="isUseDialog" draggable :close-on-click-modal="false" width="50%" :before-close="handleClose" :destroy-on-close="true">
			<template v-if="isEdit">
				<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
					<el-tab-pane label="继续上传" name="1"></el-tab-pane>
					<el-tab-pane label="已上传文件" name="2"></el-tab-pane>
				</el-tabs>
			</template>

			<template v-if="activeName === '1' || !isEdit">
				<span v-if="accept !== ''" class="text-w">注意：请上传{{ accept }}格式文件</span>
				<div style="margin-top: 10px">
					<el-upload action="#" ref="refFile" list-type="picture-card" :auto-upload="false" :accept="accept" :on-change="handleChange" multiple class="upload-s">
						<el-icon><Plus /></el-icon>
						<template #file="{ file }">
							<template v-if="file.name.split('.')[1] === 'jpeg' || file.name.split('.')[1] === 'jpg' || file.name.split('.')[1] === 'png'">
								<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
							</template>

							<template v-else>
								<span class="file-s">{{ file.name }}</span>
							</template>

							<span class="el-upload-list__item-actions set-bg" style="background-color: rgba(0, 0, 0, 0.5) !important">
								<span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)" style="background: rgba(0, 0, 0, 0) !important">
									<el-icon><Delete /></el-icon>
								</span>
							</span>
						</template>
					</el-upload>
				</div>
			</template>

			<template v-if="activeName === '2' && isEdit">
				<el-table class="heightcss" :data="fileData" style="width: 100%" v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)" border>
					<el-table-column prop="fileOriginName" label="附件名称" min-width="120" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="fileSuffix" label="文件格式" min-width="120" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="fileSizeKb" label="文件大小" min-width="100" align="center" :show-overflow-tooltip="true" />
					<el-table-column prop="filePath" label="文件路径" min-width="140" align="center" :show-overflow-tooltip="true" />
					<el-table-column fixed="right" prop="operation" label="操作" show-overflow-tooltip min-width="140" align="center">
						<template #default="scope">
							<!-- <el-link style="margin-right: 10px;" target="_blank" @click="viewClick(scope.row.id)" :href="scope.row.FilePath" type="primary">预览</el-link> -->
							<el-button @click="viewClick(scope.row)" class="icon-e" text type="success">预览</el-button>
							<el-button @click="downClick(scope.row)" class="icon-e" text type="warning">下载</el-button>
							<el-button @click="delClick(scope.row.id)" class="icon-e" text type="danger">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>

			<template #footer>
				<el-button @click="cancelUseClick">取消</el-button>
				<el-button type="primary" :loading="repeatDis" @click="submitForm">上 传</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, toRef, toRefs, toRaw, onMounted, watch } from 'vue';
import { ElButton, ElMessage } from 'element-plus';
import { sysFileInfoMultipleUpload, sysFileInfoPage, sysFileInfoDelete, sysFileInfoPreviewBase64 } from '/@/api/centerControl/pubilc';
/*** form 表单数据类型 */
export default defineComponent({
	name: 'uploadFile',
	components: {},
	props: {
		isUseDialog: {
			type: Boolean,
			default: false,
		},
		fileInfo: {
			type: String,
			default: '',
		},
		isAccept: {
			type: String,
			default: '',
		},
	},
	setup(props, ctx) {
		let fileList: any = [];
		const refFile = ref();
		const disabled = ref(false);
		const isEdit = ref(false);
		const activeName = ref('1');
		const fileData = ref();
		const loading = ref(false);
		const viewDownPath = ref('');
		const accept = ref();
		const titleCon = ref();
		const state = reactive({
			repeatDis: false,
		});

		/*** handleChange 文件上传改变事件 */
		const handleChange = (file: any) => {
			fileList.push(file);
		};

		/*** 删除文件 */
		const handleRemove = (file: any) => {
			fileList.map((itm: any, inx: number) => {
				if (file.uid === itm.uid) {
					fileList.splice(inx, 1);
				}
			});
			refFile.value.handleRemove(file);
		};

		/*** handleClose 关闭按钮点击事件 */
		const handleClose = () => {
			cancelUseClick();
		};

		/*** cancelUseClick 取消事件 */
		const cancelUseClick = () => {
			refFile.value.clearFiles();
			fileList = [];
			activeName.value = '1';
			ctx.emit('cancelFileClick');
		};

		/*** submitForm 提交事件 */
		const submitForm = () => {
			let setArr: any = [];
			if (fileList.length !== 0) {
				fileList.map((i: any) => {
					setArr.push(i.raw);
				});
				uploadFileFun(setArr, JSON.parse(props.fileInfo).id);
			} else {
				ElMessage({
					type: 'error',
					message: '请选择需要上传的文件',
					duration: 1500,
				});
			}
		};

		/*** uploadFileFun 文件上传函数 */
		const uploadFileFun = async (file: any, id: number) => {
			state.repeatDis = true;
			let param: any = {};
			param.files = file;
			param.sourceId = JSON.parse(props.fileInfo).sourceId;
			param.sourceType = JSON.parse(props.fileInfo).sourceType;
			let res: any = await sysFileInfoMultipleUpload(param);
			if (res.success) {
				ctx.emit('updateData');
				ctx.emit('controlFileClick');
			}
		};

		/*** 监听isUseDialog的变化 */
		watch(
			() => props.isUseDialog,
			(newVal) => {
				if (newVal) {
					activeName.value = '1';
					state.repeatDis = false;
					isEdit.value = false;
					accept.value = props.isAccept;
					console.log(JSON.parse(props.fileInfo), '文件信息');
					titleCon.value = JSON.parse(props.fileInfo).titleCon;
					getPageFile(JSON.parse(props.fileInfo).l_FileId);
				}
			}
		);

		/*** getPageFile 获取分页文件接口数据 */
		const getPageFile = async (id: Number) => {
			let param: any = {};
			param.PageNo = 1;
			param.PageSize = 99999;
			param.sourceId = id;
			let res: any = await sysFileInfoPage(param);
			console.log(res, 'res');
			if (res.success && res.data.rows.length !== 0) {
				console.log(res.data.rows, 'rows');
				loading.value = true;
				fileData.value = res.data.rows;
				isEdit.value = true;
				loading.value = false;
			} else {
				isEdit.value = false;
			}
		};

		/*** isUseDialog 响应弹窗的关闭  */
		const isUseDialog = computed(() => {
			return props.isUseDialog;
		});

		/*** handleClick 标签点击事件 */
		const handleClick = async (tab: any) => {
			activeName.value = toRaw(toRaw(tab).props).name;
		};

		/*** delClick 删除文件事件 */
		const delClick = async (val: Number) => {
			console.log(val, 'val');
			let param: any = {};
			param.id = val;
			let res: any = await sysFileInfoDelete(param);
			if (res.success) {
				getPageFile(JSON.parse(props.fileInfo).l_FileId);
			}
		};

		// 将Base64编码数据转换为Blob对象的辅助函数
		const base64ToBlob = (base64Data: any) => {
			var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
			var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
			var ab = new ArrayBuffer(byteString.length);
			var ia = new Uint8Array(ab);
			for (var i = 0; i < byteString.length; i++) {
				ia[i] = byteString.charCodeAt(i);
			}
			return new Blob([ab], { type: mimeString });
		};

		/*** viewClick 文件预览 */
		// const baseUrl = import.meta.env.VITE_APP_API_EQU_URL;
const baseUrl = import.meta.env.VITE_API_URL;
		const ideView = import.meta.env.VITE_APP_API_VIEW_IDE;
		const viewClick = async (val: Number) => {
			let viewUrl = baseUrl + 'api/' + val.path;
			window.open(viewUrl);
			// let getFile = getFileFun(val);
			// getFile.then(res => {
			//     window.open(res);
			// });
		};

		/*** downClick 下载文件 */
		const downClick = async (val: any) => {
			let getFile = getFileFun(val.id);
			// 等待getFileFun完成
			await getFile;
			if (getFile && getFile.then) {
				getFile.then((res) => {
					let base64Data = res;
					let blob = base64ToBlob(base64Data);

					// 创建可下载的链接
					let url = URL.createObjectURL(blob);
					let link = document.createElement('a');
					link.href = url;
					link.download = val.fileOriginName; // 指定下载的文件名

					// 将链接添加到DOM中
					document.body.appendChild(link);

					// 触发点击事件开始下载
					link.click();

					// 释放临时URL
					URL.revokeObjectURL(url);
				});
			}
		};

		/*** getFileFun 获取文件数据 */
		const getFileFun = async (val: Number) => {
			let param: any = {};
			param.id = val;
			let res: any = await sysFileInfoPreviewBase64(param);
			console.log(res, 'res');
			if (res.success) {
				return res.data;
			}
		};

		return {
			handleClose,
			submitForm,
			cancelUseClick,
			...toRefs(state),
			isUseDialog,
			handleChange,
			handleRemove,
			disabled,
			refFile,
			isEdit,
			activeName,
			handleClick,
			delClick,
			fileData,
			loading,
			viewClick,
			viewDownPath,
			downClick,
			accept,
			titleCon,
		};
	},
});
</script>
<style scoped lang="scss">
.file-s {
	padding: 10px;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}
.text-w {
	font-size: 14px;
	color: #f56c6c;
}
.upload-s {
	:deep(.el-upload--picture-card) {
		background-color: rgba(255, 255, 255, 0) !important;
	}
}
:deep(.el-button) {
	span {
		margin-left: 0px !important;
	}
}
</style>
